package com.blog.blog.service;

import com.blog.blog.dao.BlogDao;
import com.blog.blog.dto.BlogDto;
import com.blog.blog.entity.Blog;
import com.blog.util.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * TODO
 * 博客管理业务类
 * @author sean
 * @date 2020/3/28 2:23 PM
 */
@Service
public class BlogService extends BaseService{

    @Autowired
    BlogDao blogDao;

    private final static Logger logger = LoggerFactory.getLogger(BlogService.class);


    private Blog saveObj = new Blog();

    public Page<Blog> findPage(BlogDto blogDto, int pageNum, int size, String ... sortColums){
        BeanUtils.copyProperties(blogDto, saveObj);
        return blogDao.findAll(Example.of(saveObj), super.initPageable(pageNum, size, sortColums));
    }

    /**
     * 根据id保存或更新
     * @param blogDto
     * @return
     */
    public Blog saveAndUpdate(BlogDto blogDto){
        Optional<Blog> opt = blogDao.findById(blogDto.getId());
        saveObj = opt == null ? opt.get(): saveObj;
        BeanUtils.copyIgnoreNullProperties(blogDto, saveObj);
        return blogDao.saveAndFlush(this.saveObj);
    }

    public Boolean delete(long id){
        try {
            blogDao.deleteById(id);
            return true;
        }catch (Exception ex){
            return false;
        }
    }

}
